<template>
	<div class="table-main">
		<div class="titles">
			<p>季节管理</p>
			<div>
				<authCheck />
				<el-button
					size="small"
					v-if="authorize == 1"
					@click="onSeasonAdd"
					type="primary"
					>增加</el-button
				>
				<el-button size="small" @click="onDestFile" type="primary"
					>下发策略</el-button
				>
			</div>
		</div>

		<div class="table-container">
			<div class="search-container">
				<el-form :inline="true" size="small">
					<el-form-item label="储能单元：">
						<el-select
							v-model="page.ctrlGroupId"
							placeholder="请选择储能单元"
							@change="onChange"
							clearable
						>
							<el-option
								v-for="item in bmsUnitList"
								:key="item.id"
								:label="item.name"
								:value="item.id"
							>
							</el-option>
						</el-select>
					</el-form-item>
				</el-form>
			</div>
			<el-table
				:data="seasonData"
				v-loading="loading"
				style="width: 100%"
				height="calc(100% - 76px)"
				@cell-mouse-enter="handleCellEnter"
				@cell-mouse-leave="handleCellLeave"
				@cell-click="handleCellClick"
				ref="ElTableRef"
			>
				<el-table-column label="储能单元" prop="ctrlGroupId">
					<template slot-scope="scope">
						<el-select
							v-model="scope.row.ctrlGroupId"
							class="editable-cell__input"
						>
							<el-option
								v-for="item in bmsUnitList"
								:key="item.ctrlGroupId"
								:label="item.name"
								:value="item.ctrlGroupId"
							>
							</el-option>
						</el-select>
						<div class="editable-cell__val">
							{{ groupCtrlFormat(scope.row.ctrlGroupId) }}
						</div>
					</template>
				</el-table-column>
				<el-table-column label="名称" prop="name">
					<template slot-scope="scope">
						<el-input
							class="editable-cell__input"
							v-model="scope.row.name"
							placeholder="请输入内容"
						></el-input>
						<div class="editable-cell__val">{{ scope.row.name }}</div>
					</template>
				</el-table-column>
				<el-table-column label="开始日期" prop="beginDay">
					<template slot-scope="scope">
						<div class="editable-cell__val">{{ scope.row.beginDay }}</div>
						<el-date-picker
							v-model="scope.row.beginDay"
							class="editable-cell__input"
							type="date"
							format="MM月dd日"
							value-format="MM月dd日"
							placeholder="选择日期"
							style="width: 100%"
						/>
					</template>
				</el-table-column>
				<el-table-column label="结束日期" prop="endDay">
					<template slot-scope="scope">
						<div class="editable-cell__val">{{ scope.row.endDay }}</div>
						<el-date-picker
							v-model="scope.row.endDay"
							class="editable-cell__input"
							type="date"
							format="MM月dd日"
							value-format="MM月dd日"
							placeholder="选择日期"
							style="width: 100%"
						/>
					</template>
				</el-table-column>
				<el-table-column label="操作" v-if="authorize">
					<template slot-scope="scope">
						<!-- <el-button
							size="mini"
							type="normass"
							@click="handleSeasonEdit(scope.row)"
							>编辑</el-button
						> -->
						<el-button
							@click="save(scope.row)"
							v-show="scope.row.isEdit"
							type="primary"
							size="mini"
							:class="{ 'save-btn': scope.row.isEdit }"
							>保存</el-button
						>
						<!-- <el-button
							size="mini"
							v-show="scope.row.isEdit"
							type="danger"
							@click="handleEditBack()"
							>撤销更改</el-button
						> -->
						<el-button
							size="mini"
							type="danger"
							@click="handleSeasonDelete(scope.row)"
							>删除</el-button
						>
					</template>
				</el-table-column>
			</el-table>
			<div class="table-pagination">
				<el-pagination
					background
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
					:current-page="page.pageNum"
					:page-sizes="[10, 20, 30, 40]"
					:page-size="page.pageSize"
					layout="total, sizes, prev, pager, next, jumper"
					:total="total"
				>
				</el-pagination>
			</div>
		</div>
		<el-dialog
			:title="titleCostDialog"
			:visible.sync="dialogVisible"
			width="385px"
			append-to-body
			:close-on-click-modal="false"
		>
			<el-form
				ref="seasonForm"
				:model="seasonForm"
				:rules="seasonRules"
				label-width="110px"
				size="small"
			>
				<el-form-item label="储能单元：" prop="ctrlGroupId">
					<el-select
						v-model="seasonForm.ctrlGroupId"
						placeholder="请选择"
						clearable
					>
						<el-option
							v-for="item in bmsUnitList"
							:key="item.ctrlGroupId"
							:label="item.name"
							:value="item.ctrlGroupId"
						>
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="名称：" prop="name">
					<el-input
						v-model="seasonForm.name"
						placeholder="请输入名称"
						style="width: 220px"
					/>
				</el-form-item>
				<el-form-item label="起止日：" prop="beginDay">
					<el-date-picker
						v-model="seasonForm.beginDay"
						type="date"
						placeholder="选择日期"
						format="MM月dd日"
						value-format="MM月dd日"
						:editable="false"
					>
					</el-date-picker>
				</el-form-item>
				<el-form-item label="终止日：" prop="endDay">
					<el-date-picker
						v-model="seasonForm.endDay"
						type="date"
						placeholder="选择日期"
						format="MM月dd日"
						value-format="MM月dd日"
						:editable="false"
					>
					</el-date-picker>
				</el-form-item>
				<el-form-item label="复制：" prop="copyId">
					<el-select
						v-model="seasonForm.copyId"
						@change="changeCopyId"
						clearable
						placeholder="请选择"
					>
						<el-option
							v-for="item in copyBmsUnitList"
							:key="item.id"
							:label="item.showName"
							:value="item.id"
						>
						</el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitCostForm" size="small">
					确 定</el-button
				>
				<el-button @click="cancel" size="small">取 消</el-button>
			</div>
		</el-dialog>
		<!-- <el-dialog
			title="新增"
			:visible.sync="dialogVisible"
			width="385px"
			append-to-body
			:close-on-click-modal="false"
		>
			<el-form
				ref="seasonForm"
				:model="seasonForm"
				label-width="110px"
				size="small"
			>
				<el-form-item label="是否复制：" prop="addIsCopy">
					<el-checkbox v-model="seasonForm.addIsCopy"></el-checkbox>
				</el-form-item>
				<el-form-item
					label="复制："
					prop="copyId"
					v-show="seasonForm.addIsCopy"
				>
					<el-select
						v-model="seasonForm.copyId"
						@change="changeCopyId"
						clearable
						placeholder="请选择"
					>
						<el-option
							v-for="item in copyBmsUnitList"
							:key="item.id"
							:label="item.showName"
							:value="item.id"
						>
						</el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitCostForm" size="small">
					确 定</el-button
				>
				<el-button @click="cancel" size="small">取 消</el-button>
			</div>
		</el-dialog> -->
	</div>
</template>

<script>
import authCheck from "@/components/authCheck.vue";
import {
	createDestFile,
	seasonList,
	addSeason,
	deleteSeason,
	editSeason,
	copyBmsUnitList,
} from "@/api/modules/control";

export default {
	components: { authCheck },
	props: {
		bmsUnitList: [],
	},
	data() {
		return {
			loading: false,
			copyBmsUnitList: [],
			page: {
				pageNum: 1,
				pageSize: 10,
				ctrlGroupId: "",
			},
			seasonRules: {
				ctrlGroupId: [
					{
						required: true,
						message: "请选择储能单元",
						trigger: "blur",
					},
				],
				name: [
					{
						required: true,
						message: "请输入名称",
						trigger: "blur",
					},
				],
				beginDay: [
					{
						required: true,
						message: "请输入起止日",
						trigger: "blur",
					},
				],
				endDay: [
					{
						required: true,
						message: "请输入终止日",
						trigger: "blur",
					},
				],
			},
			total: 1,
			tableEditId: "",
			oldTableEditCell: null,
			seasonData: [],
			formLabelWidth: "100",
			dialogVisible: false,
			titleCostDialog: "新增",
			seasonForm: {
				addIsCopy: false,
				copyId: "",
			},
			copyItem: {},
			// editId: "",
			editProp: ["ctrlGroupId", "name", "beginDay", "endDay"],
			// 保存进入编辑的cell
			editCells: new Map(),
		};
	},
	watch: {
		bmsUnitList: {
			handler(newVal) {
				if (newVal) {
					newVal.length > 0
						? (this.page.ctrlGroupId = newVal[0].ctrlGroupId)
						: "";
					this.getData(this.page);
				}
			},
			deep: true,
		},
	},
	computed: {
		authorize() {
			if (
				this.$route.name !== "lunbo" &&
				this.$store.state.userInfo.authorize == 1
			) {
				return 1;
			} else {
				return 0;
			}
		},
	},
	created() {},
	mounted() {
		this.getCopyBmsUnitList();
	},
	methods: {
		onDestFile() {
			createDestFile().then((res) => {
				this.$message({
					type: "success",
					message: "下发策略更新成功",
				});
			});
		},
		groupCtrlFormat(row) {
			let item = this.bmsUnitList.find((item) => row == item.ctrlGroupId);
			return item ? item.name : "";
		},
		getCopyBmsUnitList() {
			copyBmsUnitList().then((res) => {
				this.copyBmsUnitList = res.data;
			});
		},
		//修改每页条数
		handleSizeChange(val) {
			this.page = {
				pageNum: 1,
				pageSize: val,
			};
			this.getData(this.page);
		},
		// 翻页
		handleCurrentChange(val) {
			this.page.pageNum = val;
			this.getData(this.page);
		},
		//选择储能单元更新数据
		onChange() {
			this.page.pageNum = 1;
			this.getData(this.page);
		},
		getData(page) {
			this.loading = true;
			seasonList(page).then((res) => {
				this.seasonData = res.rows;
				this.total = res.total;
				this.loading = false;
			});
		},

		onSeasonAdd() {
			this.titleCostDialog = "新增";
			this.dialogVisible = true;
		},

		changeCopyId(row) {
			this.copyBmsUnitList.forEach((item) => {
				if (item.id == row) {
					this.copyName = item.showName;
				}
			});
		},
		submitCostForm() {
			this.$refs.seasonForm.validate((valid) => {
				if (valid) {
					if (this.seasonForm.copyId) {
						this.$confirm(`确认使用 [${this.copyName}] 的时段数据吗?`, "提示", {
							confirmButtonText: "确定",
							cancelButtonText: "取消",
							type: "warning",
						})
							.then(() => {
								// let item = this.copyBmsUnitList.find(
								// 	(i) => i.id === this.seasonForm.copyId
								// );
								// this.save({
								// 	copyId: this.seasonForm.copyId,
								// 	ctrlGroupId: item.ctrlGroupId,
								// });
								this.submitAddForm();
							})
							.catch(() => {});
					} else {
						this.submitAddForm();
					}
				}
			});
		},
		submitAddForm() {
			// let obj = {
			// 	beginDay: "",
			// 	endDay: "",
			// 	ctrlGroupId: 1,
			// 	name: "",
			// };
			// this.seasonData.unshift(obj);
			// this.dialogVisible = false;
			addSeason(this.seasonForm).then(() => {
				this.page.pageNum = 1;
				this.getData(this.page);
				this.dialogVisible = false;
				this.cancel();
				this.$message({
					type: "success",
					message: "新增成功!",
				});
			});
		},
		/** 鼠标移入cell */
		handleCellEnter(row, column, cell, event) {
			if (this.authorize) {
				const property = column.property;
				if (this.editProp.includes(property)) {
					cell
						.querySelector(".editable-cell__val")
						.classList.add("editable-cell__val--hover");
				}
			}
		},
		/** 鼠标移出cell */
		handleCellLeave(row, column, cell, event) {
			const property = column.property;
			if (this.editProp.includes(property)) {
				cell
					.querySelector(".editable-cell__val")
					.classList.remove("editable-cell__val--hover");
			}
		},
		/** 点击cell */
		handleCellClick(row, column, cell, event) {
			if (this.authorize && column.label !== "操作") {
				// if (row.id === this.tableEditId || this.tableEditId == "") {
				// 	column.label !== "操作"
				// 		? (this.tableEditId = row.id)
				// 		: (this.tableEditId = "");
				const saveBtns =
					this.$refs.ElTableRef.$el.querySelectorAll(".save-btn");
				if (saveBtns.length > 0 && row.id !== this.tableEditId) {
					this.$message({
						type: "info",
						message: "请先保存数据",
					});
					return;
				}
				if (this.oldTableEditCell !== cell && this.oldTableEditCell !== null) {
					this.cancelEditable(this.oldTableEditCell);
				}
				this.oldTableEditCell = cell;
				this.tableEditId = row.id;

				const property = column.property;
				if (this.editProp.includes(property)) {
					// 保存cell
					this.saveCellClick(row, cell);
					cell.querySelector(".editable-cell__val").style.display = "none";
					cell.querySelector(".editable-cell__input").style.display = "block";
					cell.querySelector("input").focus();
				}
				// } else {
				// 	this.$message({
				// 		type: "warnning",
				// 		message: "请先保存数据!",
				// 	});
				// }
			}
		},
		/** 取消编辑状态 */
		cancelEditable(cell) {
			cell.querySelector(".editable-cell__val").style.display = "block";
			cell.querySelector(".editable-cell__input").style.display = "none";
		},
		/** 保存进入编辑的cell */
		saveCellClick(row, cell) {
			if (this.editCells.has(row)) {
				this.editCells.get(row).add(cell);
			} else {
				this.editCells.set(row, new Set([cell]));
			}
			this.updateRowSave(row);
		},
		updateRowSave(row) {
			// this.seasonData.map((item) => {
			// 	if (item.id == row.id) {
			// 		this.$set(item, "isEdit", this.editCells.has(row));
			// 	}
			// });
			row.isEdit = this.editCells.has(row);
		},
		/** 保存数据 */
		save(row) {
			if (row.isEdit) {
				delete row.isEdit;
			}
			if (row.id) {
				//编辑
				// let obj = this.seasonForm;
				// obj.id = this.editId;
				editSeason(row).then(() => {
					this.getData(this.page);
					this.cancel();
					this.$message({
						type: "success",
						message: "修改成功!",
					});
					this.saveSuccess(row);
				});
			} else {
				addSeason(row).then(() => {
					this.page.pageNum = 1;
					this.getData(this.page);
					this.cancel();
					this.$message({
						type: "success",
						message: "新增成功!",
					});
					this.getCopyBmsUnitList();
					this.saveSuccess(row);
				});
			}
		},
		saveSuccess(row) {
			this.tableEditId = "";
			this.oldTableEditCell = null;
			this.editCells.get(row).forEach((cell) => {
				this.cancelEditable(cell);
			});
			this.editCells.delete(row);
			this.updateRowSave(row);
		},
		cancel() {
			this.seasonForm = {
				copyId: "",
				addIsCopy: false,
			};
			this.dialogVisible = false;
		},
		handleSeasonDelete(row) {
			this.$confirm("确定删除此数据吗?", "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning",
			})
				.then(() => {
					if (row.id) {
						deleteSeason(row.id).then((res) => {
							this.getData(this.page);
							this.$message({
								type: "success",
								message: "删除成功!",
							});
							this.$emit("updataTactic");
						});
					} else {
						this.seasonData.shift();
						this.getData(this.page);
						this.cancelAllEdit();
					}
				})
				.catch(() => {
					this.$message({
						type: "info",
						message: "已取消删除",
					});
				});
		},
		cancelAllEdit() {
			const inputs = this.$refs.ElTableRef.$el.querySelectorAll(
				".editable-cell__input"
			);
			inputs.forEach((input) => {
				input.style.display = "none";
			});
			const vals = this.$refs.ElTableRef.$el.querySelectorAll(
				".editable-cell__val"
			);
			vals.forEach((val) => {
				val.style.display = "block";
			});
		},
	},
};
</script>
<style lang="scss" scoped>
.titles {
	display: flex;
	justify-content: space-between;
	.el-button--primary {
		background-color: #045eed;
		border-color: #045eed;
		margin: 10px 10px 0 0;
	}
	.el-button {
		margin: 9px 10px 0 0;
	}
}

.table-main {
	height: calc(100% - 55px);
	.table-container {
		padding: 10px 22px;
		height: calc(100% - 56px);
		width: calc(100% - 30px);
	}
	.el-pagination {
		padding: 10px 5px 2px;
	}
}
.editable-cell__input {
	display: none;
	.el-input__inner {
		padding: 0 8px;
		font-size: 12px;
	}
}

.editable-cell__val {
	box-sizing: border-box;
	height: 32px;
	line-height: 32px;
	border: 1px solid transparent;

	&--hover {
		border-color: #dddddd;
		border-radius: 4px;
		cursor: text;
	}
}
</style>
